<?php

namespace App\Http\Resources\OpenShop\StartBusiness;

use App\Enums\OpenShop\InvestmentPromotion\UploadFileResourceEnum;
use App\Http\Resources\BaseResource;
use App\Models\OpenShop\InvestmentPromotion\OpenShopLocationModel;
use App\Models\OpenShop\StartBusiness\OpenShopStartBusinessModel;
use App\Remote\Rms\RmsShopRemote;
use Illuminate\Http\Request;

class StartBusinessResource extends BaseResource
{
    /**
     * Transform the resource into an array.
     *
     * @param Request $request
     * @return array
     */
    public function toArray($request): array
    {
        try {
            $branchCompany = $this
                ->mainProcessRel
                ->shopLocationRel
                ->organizationRegionMappingRel
                ->organizationManageRel
                ->name;
        } catch (\Exception $e) {
            $branchCompany = '';
        }

        return array_merge([
            "orderNo"                   => $this->orderNo,
            "branchCompany"             => $branchCompany,
            "step"                      => $this->step,
            "eatInTotal"                => $this->eatInTotal,
            "hasMonitorUint"            => $this->hasMonitorUint,
            "hasMonitorUintText"        => translateEnumCodeToCn(
                OpenShopStartBusinessModel::MONITOR_UNIT_MAP,
                $this->hasMonitorUint
            ),
            "hasRight"                  => $this->hasRight,
            "hasRightText"              => translateEnumCodeToCn(
                OpenShopStartBusinessModel::RIGHT_MAP,
                $this->hasRight
            ),
            "rightDetail"               => $this->rightDetail,
            "sellChannel"               => $this->sellChannel,
            "sellChannelText"           => $this->getJsonColumnMap(
                $this->sellChannel,
                OpenShopStartBusinessModel::SELL_CHANNEL_MAP
            ),
            "employmentExperience"      => $this->employmentExperience,
            "employmentExperienceText"  => translateEnumCodeToCn(
                OpenShopStartBusinessModel::EMPLOYMENT_EXPERIENCE_MAP,
                $this->employmentExperience
            ),
            "managementInput"           => $this->managementInput,
            "managementInputText"       => translateEnumCodeToCn(
                OpenShopStartBusinessModel::MANAGEMENT_INPUT_TYPE_MAP,
                $this->managementInput
            ),
            "degreeCooperation"         => $this->degreeCooperation,
            "degreeCooperationText"     => translateEnumCodeToCn(
                OpenShopStartBusinessModel::DEGREE_COOPERATION_TYPE,
                $this->degreeCooperation
            ),
            "startBusinessTime"         => formatDateYmd($this->startBusinessTime),
            "sellPriceType"             => $this->sellPriceType,
            "sellPriceTypeText"         => translateEnumCodeToCn(
                OpenShopStartBusinessModel::SELL_PRICE_TYPE,
                $this->sellPriceType
            ),
            "menuCategory"              => $this->menuCategory,
            "menuCategoryText"          => $this->getJsonColumnMap(
                $this->menuCategory,
                OpenShopStartBusinessModel::MENU_CATEGORY_TYPE
            ),
            "staffCount"                => $this->staffCount,
            "monthlyWages"              => $this->monthlyWages,
            "startBusinessActivityDesc" => $this->startBusinessActivityDesc,
            "promoteChancePointDesc"    => $this->promoteChancePointDesc,
            "leaveBehindQuestionDesc"   => $this->leaveBehindQuestionDesc,
            "startShopPic"              => json_decode($this->startShopPic, true) ?? [],
            "startHotMv"                => json_decode($this->startHotMv, true) ?? [],
        ], $this->getAttachFileInfo(UploadFileResourceEnum::START_BUSINESS_MAP), $this->getStartBusinessGroup());
    }

    public function getStartBusinessGroup()
    {
        $mobile        = $this->userBaseInfoRel->mobile;
        $shopCode      = $this->signOrderRel->shopCode;
        $groupBusiness = RmsShopRemote::getOpenShopStartBusiness($shopCode, $mobile, $this->startBusinessTime);
        $groupStatic   = $groupBusiness["dataStatic"] ? collect($groupBusiness["dataStatic"]) : null;
        $predictDayPay = ($groupStatic == null ? 0 :
            (int)$groupStatic->sum("realPayPriceSum") / $groupStatic->count());

        $shopRent      = $this->getShopRent($predictDayPay, $this->mainProcessRel->shopLocationRel);
        return [
            "shopCount"       => count($groupBusiness["shopList"] ?? []),
            "isFirstShop"     => count($groupBusiness["shopList"]) == 1,
            "branch"          => $groupBusiness["shopInfo"] ? $groupBusiness["shopInfo"]["branch"] : "",
            "groupBusiness"   => $groupStatic == null ? [] : $groupStatic->toArray(),
            "avgVolume"       =>
                $groupStatic == null ? 0 :
                    (int)($groupStatic->sum("orderSum") / $groupStatic->count()),
            "avgOrderOrginal" =>
                $groupStatic == null ? 0 :
                    (int)($groupStatic->sum("originalPriceSum") / $groupStatic->sum("orderSum")),
            "avgOrderPay"     =>
                $groupStatic == null ? 0 :
                    (int)($groupStatic->sum("realPayPriceSum") / $groupStatic->sum("orderSum")),
            "avgDayOrginal"   =>
                $groupStatic == null ? 0 :
                    (int)($groupStatic->sum("originalPriceSum") / $groupStatic->count()),
            "avgDayPay"       => $predictDayPay,
            "predictMonthPay" => (int)($predictDayPay * 31),
            "roi"             => (int)
            ($shopRent > 0 ? (($predictDayPay * 31) / $shopRent) : 0),
            "predictProfit"   => (int)($predictDayPay * 31
                - $shopRent
                - $this->monthlyWages
                - ($predictDayPay * 31) * 0.35)
        ];


    }

    public function getShopRent($predictDayPay, $shopLocation)
    {
        $shopRentMonth = 0;
        switch ($shopLocation->monthlyRent) {
            case OpenShopLocationModel::MONTH_RENT_0:
                $shopRentMonth = $shopLocation->shopRent;
                break;
            case OpenShopLocationModel::MONTH_RENT_1:
                $shopRentMonth = $predictDayPay * 31 * $shopLocation->monthlyRent;
                break;
            case OpenShopLocationModel::MONTH_RENT_2:
                $shopRentMonth = $predictDayPay * 31 * $shopLocation->monthlyRent + $shopLocation->shopRent;
                break;
        }
        return $shopRentMonth > 0 ? $shopRentMonth / 100 : 0;
    }


    /**
     * 获取json对应数组映射值
     *
     * @param string $json
     * @param array $original
     * @return string
     */
    public function getJsonColumnMap(string $json, array $original)
    {
        return ($json && $now = json_decode($json, true)) ?
            collect($original)->only($now)->values()->implode(",") : "-";
    }
}
